'use strict';
const cloud = require('wx-server-sdk');
const { uniID } = require('uni-id-common');

cloud.init();
const db = cloud.database();

exports.main = async (event, context) => {
  // 初始化uniID
  const uniIDIns = uniID.createInstance({ context });
  
  const { phone } = event;
  
  // 参数验证
  if (!phone) {
    return {
      code: 400,
      message: '请输入手机号'
    };
  }
  
  // 简单的手机号格式验证
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(phone)) {
    return {
      code: 400,
      message: '手机号格式不正确'
    };
  }
  
  try {
    // 检查手机号是否已注册
    const userRes = await db.collection('uni-id-users')
      .where({
        phone: phone
      })
      .get();
      
    if (userRes.data.length === 0) {
      return {
        code: 10003,
        message: '手机号未注册'
      };
    }
    
    // 发送验证码
    const sendCodeRes = await uniIDIns.sendSmsCode({
      phone,
      type: 'reset-pwd' // 重置密码类型的验证码
    });
    
    if (sendCodeRes.code !== 0) {
      return sendCodeRes;
    }
    
    return {
      code: 0,
      message: '验证码发送成功'
    };
    
  } catch (error) {
    console.error('发送验证码失败:', error);
    return {
      code: 500,
      message: '发送验证码失败，请稍后重试'
    };
  }
};